//
//  ClientiViewController.m
//  iTeVe
//
//  Created by Pedro Gonzalez on 03/02/14.
//  Copyright (c) 2014 SISI Software. All rights reserved.
//

#import "ClientiViewController.h"
#import "FMDBDataAccess.h"
#import "ClienteCell.h"
#import "Utility.h"

@interface ClientiViewController ()

@end

@implementation ClientiViewController

NSMutableDictionary *sections;


@synthesize searchClienti;

@synthesize myTableView;



- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    searchClienti.delegate = (id)self;
    searchClienti.placeholder = self.title = NSLocalizedString(@"CERCA_CLIENTE", @"Testo Cerca...");
    self.navigationItem.title = NSLocalizedString(@"ANAGRAFICA_CLIENTI", @"Anagrafica clienti...");
    self.navigationItem.prompt = @"iTeVe";

    [self populateClienti:@""];
    
}


-(void)searchBar:(UISearchBar*)searchClienti textDidChange:(NSString*)text
{
    if(text.length > 0){
        [self populateClienti:text];
    } else {
        [self populateClienti:@""];
    }
    
    [self.tableView reloadData];
}


-(void) populateClienti:(NSString *)filtro
    {
        clienti = [[NSMutableArray alloc] init];
        
        FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
        
        clienti = [db getClienti:filtro :nil];
    }


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [clienti count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ClienteCell";
    
    ClienteCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    Cliente *cliente = [clienti objectAtIndex:[indexPath row]];
    cell.ragionesociale.text = cliente.ragionesociale;
    NSString *ind = [NSString stringWithFormat:@"%@ %@ %@ %@ %@", cliente.indirizzo, cliente.cap.length==0?@"":[NSString stringWithFormat:@"(%@)",cliente.cap], cliente.citta, cliente.provincia, cliente.nazione];
    cell.indirizzo.text = ind;
    cell.telefono.text = cliente.telefono;
    cell.email.text = cliente.email;
    return cell;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // cancello cliente
    [Utility showAlert:@"Info" message:@"Non si possono cancellare i clienti" ];
    
}

            
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    // Find the correct index of cell should scroll to.
    int foundIndex = 0;
    for (Cliente *obj in clienti) {
        if ([[[obj.ragionesociale substringToIndex:1] uppercaseString] compare:title] == NSOrderedSame || [[[obj.ragionesociale substringToIndex:1] uppercaseString] compare: title] == NSOrderedDescending)
            break;
        foundIndex++;
    }
    if(foundIndex >= [clienti count])
        foundIndex = (int)[clienti count]-1;
    
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    return 1;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"segueClienteDetail"]) {
        
        Cliente *cliente = [clienti objectAtIndex:[self.tableView indexPathForCell:sender].row];
        cliente.nuovo = [NSNumber numberWithBool:NO];
        UINavigationController *navigationController = segue.destinationViewController;
        ClienteDVStaticViewController *destViewController = [navigationController viewControllers][0];
        destViewController.modelCliente = cliente;
        destViewController.delegate = self;
    }
    else if ([segue.identifier isEqualToString:@"segueAddCliente"]) {
        UINavigationController *navigationController = segue.destinationViewController;
        ClienteDVStaticViewController *destViewController = [navigationController viewControllers][0];
        Cliente *cliente = [[Cliente alloc] init];
        cliente.sc1 = [NSNumber numberWithDouble:0];
        cliente.sc2 = [NSNumber numberWithDouble:0];
        cliente.sc3 = [NSNumber numberWithDouble:0];
        cliente.sc4 = [NSNumber numberWithDouble:0];
        cliente.nuovo = [NSNumber numberWithBool:YES];
        destViewController.modelCliente = cliente;
        destViewController.delegate = self;
    }
    
}




-(void) clienteDVStaticViewControllerDidCancel:(ClienteDVStaticViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void) clienteDVStaticViewControllerDidSave:(ClienteDVStaticViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void) clienteDVStaticViewController:(ClienteDVStaticViewController *)controller didEditCliente:(Cliente *)cliente
{
    FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
    
    cliente.ultimamodifica = [NSDate date];
    
    [db updateCliente:cliente];

    NSString *text = searchClienti.text;
    if(text.length > 0){
        [self populateClienti:text];
    } else {
        [self populateClienti:@""];
    }
    
    [self.tableView reloadData];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}



-(void) clienteDVStaticViewController:(ClienteDVStaticViewController *)controller didAddCliente:(Cliente *)cliente
{
    FMDBDataAccess *db = [[FMDBDataAccess alloc] init];

    cliente.ultimamodifica = [NSDate date];
    
    [db insertCliente:cliente];
    
    NSString *text = searchClienti.text;
    if(text.length > 0){
        [self populateClienti:text];
    } else {
        [self populateClienti:@""];
    }
    
    
    [self.tableView reloadData];
/*
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[clienti count] - 1 inSection:0];
    
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
 */
    
    [self dismissViewControllerAnimated:YES completion:nil];
}





@end
